#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include "connect.h"
#include "getmessages.h"
#include "sendmessage.h"
#include "changestatus.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pgsql/libpq-fe.h>

int main(int argc, char* argv[]){
  extern PGconn *conn;
    extern char lasttime[];
	extern char fristtime[];
	char getbuffer[2048], sendbuffer[2048];
	pid_t pid;
	if(!conn)	conn = dbconnect();

	if((pid = fork()) < 0){
    fprintf(stderr, "ERROR: 进程创建失败!\n");
    exit(1);
	}
	else if(pid == 0){
    while(1){
      getmessages(getbuffer, 2);
      printf("%s\n", getbuffer);
      if(strcmp(lasttime, fristtime) && strcmp(lasttime, "")){
        if(changestatus(lasttime)){
          sprintf(fristtime, "%s", lasttime);
        }
      }
      sleep(2);
    }
	}
	else{
		while(1){
			scanf("%s", sendbuffer);
			if(!strcmp("q", sendbuffer)){
				kill(pid, SIGKILL);
				exit(0);
			}
			else{
				sendmessage(2, sendbuffer);
			}
		}
	}
  PQfinish(conn);
  return 0;
}
